#!/usr/bin/python3
# -*- coding: utf-8 -*-

import logging; logging.basicConfig(level=logging.INFO)
from aiohttp import web
from routes import setup_routes, setup_static_routes
from settings import config, BASE_DIR
from db import init_db, close_db
from middlewares import setup_middlewares
import aiohttp_jinja2
import jinja2, os

def datetime_filter(t):
    return t.strftime("%Y-%m-%d %H:%M:%S")

def init_jinja(app):
    path = os.path.join(BASE_DIR, 'www/templates')
    filters = dict(datetime=datetime_filter)
    # 拦截器中手动渲染
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(path))
    env.filters = dict(env.filters, **filters)
    app['__templating__'] = env
    loader_ = jinja2.FileSystemLoader(path)
    # 修饰器自动渲染@aiohttp_jinja2.template
    aiohttp_jinja2.setup(app, loader=loader_, filters=filters)

def init():
    app = web.Application()
    app['config'] = config
    logging.info('[+]config: %s' % config)
    init_jinja(app)
    setup_routes(app)
    setup_static_routes(app)
    setup_middlewares(app)
    app.on_startup.append(init_db)
    # app.on_cleanup.append(close_db)
    web.run_app(app)

if __name__ == '__main__':
    init()